import axios, { AxiosError } from 'axios'
import { message } from 'ant-design-vue'
import { FrontApiResp } from './FrontApiResp'

export function buildApiUrl(uri: string) {
  return `${window.API_PREFIX}${uri}`
}
function apiAxiosInstance() {
  const axiosInstance = axios.create()
  axiosInstance.interceptors.response.use(
    response => {
      const requestConfig = response.config
      const { data, statusCode, message: msg } = response.data
      console.log('data', data)
      console.log('statusCode', statusCode)
      console.log('message', msg)
      if ([200, 201].indexOf(statusCode) < 0) {
        message.error(msg)
        throw message
      }
      return data
    },
    error => {
      const resp = extractRespDataFromError(error)
      if (resp && resp.message) {
        message.error(Array.isArray(resp.message) ? resp.message.join(' , ') : resp.message)
        throw resp.message
      }
      throw error
    }
  )
  return axiosInstance
}

function extractRespDataFromError(error: AxiosError) {
  if (error.response && error.response.data) {
    return error.response.data as FrontApiResp<void>
  }
  return undefined
}

export const serviceApiAxiosInstance = apiAxiosInstance()

export async function reqGet<T>(url: string, data: unknown): Promise<T> {
  return (await serviceApiAxiosInstance.get<T>(url, { params: data })) as T
}

export async function reqPost<T>(url: string, data?: unknown): Promise<T> {
  return (await serviceApiAxiosInstance.post<T>(url, data)) as T
}

export async function reqPut<T>(url: string, data: unknown): Promise<T> {
  return (await serviceApiAxiosInstance.put<T>(url, data)) as T
}

export async function reqDelete<T>(url: string, data: unknown): Promise<T> {
  return (await serviceApiAxiosInstance.delete<T>(url, { params: data })) as T
}
